package jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author oldliu
 * @since 1.0
 */
public class StuShumu {
    public static void main(String[] args) {
        //统计学生人数
         //select count('x') from s_stu
        int i=zhuanzhang("hf002","hf001",100);
        System.out.println(i);
    }
    public static int zhuanzhang(String from,String to,double money){
        Connection connection = DBUtil.getConnection();
        PreparedStatement ps =null;
        ResultSet rs=null;
        try {
            connection.setAutoCommit(false);//关闭自动提交
            String sql="update bank set balance=balance-? where no=?";
            //String sql2="update bank set balance+? where no=?";
            ps=connection.prepareStatement(sql);
            ps.setDouble(1,money);
            ps.setString(2,from);
            //
            ps.addBatch();
            ps.setDouble(1,-money);
            ps.setString(2,to);
            ps.addBatch();
            //批处理
            int[] res = ps.executeBatch();
            if(res[0]>0 &&res[1]>0)
                connection.commit();
            else
                connection.rollback();

            return res[0]*res[1];
        } catch (SQLException e) {
            try {
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            DBUtil.close(connection,ps,null);
        }
        return 0;
    }
}
